﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using BoYuanCore.Framework.Extensions;

namespace BoYuanCore.Framework.StringUtility
{
    /// <summary>
    /// html相关字符串操作
    /// </summary>
    public class HTMLTag
    {
        /// <summary>
        /// 获取a标签的html
        /// </summary>
        /// <param name="href">url地址</param>
        /// <param name="fileName">a标签内容(文本或img等)</param>
        /// <param name="target">target属性(_blank,_self,_parent,_top)</param>
        /// <param name="title">标题</param>
        /// <returns></returns>
        public static string GetHtmlA(string href, string fileName, string target = "", string title = "")
        {
            if (string.IsNullOrEmpty(href) || string.IsNullOrEmpty(fileName)) return string.Empty;

            string[] targetList = new[] { "_blank", "_self", "_parent", "_top" };
            if (target.Length > 0)
            {
                target = targetList.Contains(target, StringComparison.OrdinalIgnoreCase)
                ? " target='" + target.ToLower() + "'"
                : string.Empty;
            }

            if (title.Length > 0) { title = " title='{3}'"; }

            return string.Format("<a href='{0}'{2}>{1}</a>", href, fileName, title + target);
        }

        /// <summary>
        /// 获取执行js的a标签html
        /// </summary>
        /// <param name="js">js方法名称</param>
        /// <param name="fileName">a标签名称</param>
        /// <returns></returns>
        public static string GetHtmlAJs(string js, string fileName)
        {
            if (string.IsNullOrWhiteSpace(js)) return fileName;
            if (string.IsNullOrEmpty(fileName)) return string.Empty;
            //a href="javascript:void(0);" onclick="js_method()"
            //a href="javascript:;" onclick="js_method()"
            return string.Format("<a href='javascript:;' onclick=\"{0}\">{1}</a>", js, fileName);
        }

        /// <summary>
        /// 获取图片html
        /// </summary>
        /// <param name="src">js方法名称</param>
        /// <param name="title"></param>
        /// <param name="alt"></param>
        /// <param name="attr">其他标签</param>
        /// <returns></returns>
        public static string GetHtmlImg(string src, string title = "", string alt = "", string attr = "")
        {
            if (string.IsNullOrEmpty(src)) return string.Empty;
            return string.Format("<img src='{0}'{1}{2} {3}/>", src, title.Length > 0 ? " title='" + title + "'" : " ", alt.Length > 0 ? " alt='" + alt + "'" : " ", attr);
        }

        /// <summary>
        /// 匹配页面的图片地址
        /// </summary>
        /// <param name="imgHttp">要补充的http://路径信息</param>
        public string GetImgSrc(string HtmlCode, string imgHttp)
        {
            string MatchVale = "";
            string Reg = @"<img.+?>";
            foreach (Match m in Regex.Matches(HtmlCode.ToLower(), Reg))
            {
                MatchVale += GetImg((m.Value).ToLower().Trim(), imgHttp) + "|";
            }

            return MatchVale;
        }

        /// <summary>
        /// 匹配<img src="" />中的图片路径实际链接
        /// </summary>
        /// <param name="ImgString"><img src="" />字符串</param>
        public string GetImg(string ImgString, string imgHttp)
        {
            string MatchVale = "";
            string Reg = @"src=.+\.(bmp|jpg|gif|png|)";
            foreach (Match m in Regex.Matches(ImgString.ToLower(), Reg))
            {
                MatchVale += (m.Value).ToLower().Trim().Replace("src=", "");
            }
            if (MatchVale.IndexOf(".net") != -1 || MatchVale.IndexOf(".com") != -1 || MatchVale.IndexOf(".org") != -1 || MatchVale.IndexOf(".cn") != -1 || MatchVale.IndexOf(".cc") != -1 || MatchVale.IndexOf(".info") != -1 || MatchVale.IndexOf(".biz") != -1 || MatchVale.IndexOf(".tv") != -1)
                return (MatchVale);
            else
                return (imgHttp + MatchVale);
        }

        /// <summary>
        /// 获取单个href值
        /// </summary>
        /// <param name="htmlCode"></param>
        /// <returns></returns>
        public static string GetHrefSingle(string htmlCode)
        {
            string reg = @"<a[^>]*href=([""'])?(?<href>[^'""]+)\1[^>]*>";
            var item = Regex.Match(htmlCode, reg, RegexOptions.IgnoreCase);
            return item.Groups["href"].Value;
        }

        /// <summary>
        /// 获取单个href值
        /// </summary>
        /// <param name="htmlCode"></param>
        /// <returns></returns>
        public static string GetSingleHref(string htmlCode)
        {
            string reg = @"<a[^>]*href=([""'])?(?<href>[^'""]+)\1[^>]*>";
            var item = Regex.Match(htmlCode, reg, RegexOptions.IgnoreCase);
            return item.Groups["href"].Value;
        }

        /// <summary>
        /// 获取多个href值
        /// </summary>
        /// <param name="htmlCode"></param>
        /// <returns></returns>
        public static List<string> GetHrefList(string htmlCode)
        {
            string reg = @"<a[^>]*href=([""'])?(?<href>[^'""]+)\1[^>]*>";
            MatchCollection matches = Regex.Matches(htmlCode, reg, RegexOptions.IgnoreCase);
            List<string> hrefList = new List<string>();
            foreach (Match item in matches)
            {
                hrefList.Add(item.Groups[1].Value);
            }

            return hrefList;
        }

        /// <summary>
        /// 过滤指定HTML标签
        /// </summary>
        /// <param name="htmlStr">原html</param>
        /// <param name="tags">要过滤的标签集合(例如 script style div等)</param>
        public static string FilterHtmlTags(string htmlStr, IEnumerable<string> tags)
        {
            string rStr = string.Empty;
            //string regexStr = @"(\<script(.+?)\</script\>)|(\<style(.+?)\</style\>)";

            if (tags == null || !tags.Any())
            {
                return htmlStr;
            }

            StringBuilder sb = new StringBuilder();
            foreach (var tag in tags)
            {
                sb.AppendFormat(@"|(\<{0}(.+?)\</{0}\>)", tag);
            }

            string regexStr = sb.ToString().Substring(1);

            if (!string.IsNullOrEmpty(htmlStr))
            {
                rStr = Regex.Replace(htmlStr, regexStr, string.Empty, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            }
            return rStr;
        }

        /// <summary>
        /// 判断是否是图片标签
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static bool IsImg(string Url)
        {
            return Regex.IsMatch(Url, @"(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$");
        }

        ///<summary> 
        ///TextBox文本转成html字符实体 
        ///</summary> 
        ///<param  name="text">TextBox文本</param> 
        ///<returns></returns> 
        public static string TextBoxToHtml(string text)
        {
            StringBuilder sb = new StringBuilder(text);
            sb.Replace("&", "&amp");
            sb.Replace("\"", "&quot;");
            sb.Replace(" ", "&nbsp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\n", "<br/>");
            return sb.ToString();
        }

        /// <summary>
        /// html字符实体还原
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string HtmlToTextBox(string html)
        {
            StringBuilder sb = new StringBuilder(html);
            sb.Replace("<br/>", "\n");
            sb.Replace("&gt;", ">");
            sb.Replace("&lt;", "<");
            sb.Replace("&nbsp;", " ");
            sb.Replace("&quot;", "\"");
            sb.Replace("&amp", "&");
            return sb.ToString();
        }
    }
}
